<template>
  <el-dialog
    top="30px"
    width="800px"
    append-to-body
    :close-on-click-modal="false"
    :before-close="beforeClose"
    :visible.sync="visible"
  >
    <div slot="title">
      <span class="wl-title">受理白名单项目</span>
      <span class="text-sm text-muted">（{{ whiteData.project_type_name }}）</span>
    </div>
    <table class="table table-borderless table-sm">
      <tbody>
        <tr>
          <td width="16%" class="text-muted">项目名称：</td>
          <td width="34%">{{ whiteData.customer_name }}</td>
          <td width="16%" class="text-muted">项目地址：</td>
          <td width="34%">{{ whiteData.address }}</td>
        </tr>
        <tr>
          <td class="text-muted">负责人：</td>
          <td>{{ whiteData.corp_name }}</td>
          <td class="text-muted">联系电话：</td>
          <td>{{ whiteData.mobile_no }}</td>
        </tr>
        <tr>
          <td class="text-muted">申请机构：</td>
          <td>{{ whiteData.submit_person_name || '-' }}</td>
          <td class="text-muted">申请时间：</td>
          <td>{{ applayDate }}</td>
        </tr>
        <tr>
          <td class="text-muted">
            <span class="text-danger">*</span>
            申请金额：
          </td>
          <td colspan="3">
            <el-input
              placeholder="申请金额"
              class="form-control-ml"
              v-input-number="{ min: 0, fixed: 0 }"
              v-model="formData.apply_funds"
            >
              <template slot="append">万元</template>
            </el-input>
          </td>
        </tr>
        <tr>
          <td class="text-muted">
            <span class="text-danger">*</span>
            申请年限：
          </td>
          <td colspan="3">
            <el-input
              placeholder="申请年限"
              class="form-control-ml"
              v-input-number="{ min: 0, fixed: 0, max: 100 }"
              v-model="formData.load_years"
            >
              <template slot="append">年</template>
            </el-input>
          </td>
        </tr>
        <tr>
          <td class="text-muted">
            <span class="text-danger">*</span>
            贷款用途：
          </td>
          <td colspan="3">
            <el-input
              placeholder="贷款用途"
              class="form-control-ml"
              type="textarea"
              :rows="5"
              v-model="formData.funds_use_dir"
            ></el-input>
          </td>
        </tr>

        <tr>
          <td class="text-muted pt-2">
            <span class="text-danger">*</span>
            业务类型：
          </td>
          <td colspan="3">
            <span v-if="!isUserTown" class="pt-2">直担业务</span>
            <select-gua-type
              v-else
              placeholder="请选择项目类型"
              class="form-control-ml"
              v-model="formData.gua_type"
            ></select-gua-type>
          </td>
        </tr>
        <tr v-show="needAccessAgency">
          <td class="text-muted">
            <span class="text-danger">*</span>
            联保机构：
          </td>
          <td colspan="3">
            <select-org-credit
              v-model="formData.recommend_service"
              @change="handleAccessAgencyChange"
              :gua-type="formData.gua_type"
              class="form-control-ml"
              placeholder="请选择联保机构"
            ></select-org-credit>
          </td>
        </tr>

        <tr>
          <td class="text-muted pt-2">
            <span class="text-danger">*</span>
            项目负责人A角：
          </td>
          <td colspan="3">
            <select-staff
              v-model="formData.res_a"
              ref="resA"
              class="form-control-ml"
              placeholder="请选择A角"
            ></select-staff>
          </td>
        </tr>
        <tr>
          <td class="text-muted pt-2">
            <span class="text-danger">*</span>
            项目负责人B角：
          </td>
          <td colspan="3">
            <select-staff
              v-model="formData.res_b"
              ref="resB"
              class="form-control-ml"
              placeholder="请选择B角"
            ></select-staff>
          </td>
        </tr>
        <tr v-if="[4].includes(+formData.gua_type)">
          <td class="text-muted pt-2">
            <span class="text-danger">*</span>
            风控员：
          </td>
          <td colspan="3">
            <select-staff
              v-model="formData.res_user_id_risk_point"
              :includeJob="['org_r_emp', 'org_r_manage', 'org_dg_risk_manage']"
              ref="risk"
              class="form-control-ml"
              placeholder="请选择项目风控员"
            ></select-staff>
          </td>
        </tr>

        <tr v-if="![2, 4].includes(+formData.gua_type)">
          <td class="text-muted pt-2">选择指定银行：</td>
          <td colspan="3">
            <select-org-bank
              v-model="formData.public_bank_ids"
              @select="handleSelectBank"
              filterable
              class="form-control-ml"
            ></select-org-bank>
          </td>
        </tr>
        <tr v-else>
          <td class="text-muted pt-2">合作银行：</td>
          <td colspan="3">
            <select-org-bank
              v-model="formData.bank_id"
              @select="handleSelectBankId"
              placeholder="合作银行（非必填）"
              filterable
              class="form-control-ml"
            ></select-org-bank>
          </td>
        </tr>
      </tbody>
    </table>

    <div class="text-center mt-5">
      <el-button @click="submit" type="primary" :loading="submitLoading" class="btn-long">
        确认受理
      </el-button>
      <el-button @click="beforeClose" class="btn-long">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
// import { enumApprovalGuaType } from '@/credit/plugins/enumTown'
import SelectGuaType from '@/credit/components/select/SelectGuaType'

import SelectStaff from '@/components/select/SelectStaff'
import SelectOrgBank from '@/credit/components/select/SelectOrgBank'
import { provinceGoodsServiceId } from '@/credit/views/province/goods/goodsMixins'
import SelectOrgCredit from '@/credit/components/select/SelectOrgCredit'
export default {
  components: {
    SelectGuaType,
    SelectStaff,
    // SelectBanks,
    SelectOrgBank,
    SelectOrgCredit,
  },
  props: {
    visible: Boolean,
    whiteData: {
      type: Object,
      default: () => ({}),
    },
    industrialPackage: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      tableName: 'customer_related',
      formData: {
        gua_type: 2,
        res_a: '',
        res_a_name: '',
        res_b: '',
        res_b_name: '',
        res_user_id_risk_point: '',
        res_person_risk_point: '',
        public_bank_ids: '',
        public_bank_names: '',
      },
      submitLoading: false,
    }
  },
  computed: {
    ...mapGetters(['userId', 'user', 'clientId', 'org']),
    // 是否需要选择联保机构
    needAccessAgency() {
      return this.formData.gua_type && +this.formData.gua_type !== 2
    },
    isUserTown() {
      return [3, 2].includes(this.user.orgRegionLever)
    },
    isProvince() {
      return +this.user.orgRegionLever === 1
    },
    applayDate() {
      let data = ''
      if (+this.whiteData.pro_approval === 1) {
        data = this.whiteData.pro_approval_time
      } else if (+this.whiteData.city_approval === 1) {
        data = this.whiteData.city_approval_time
      } else {
        data = this.whiteData.county_approval_time
      }
      return this.$utils.dateFormat(data, 'yyyy.MM.dd') || '-'
    },
    isRoutine() {
      if (!this.isUserTown) {
        return false
      }
      if (
        +this.formData.gua_type === 4 &&
        this.industrialPackage.service_id !== provinceGoodsServiceId
      ) {
        return true
      }
      return false
    },
  },
  watch: {
    visible() {
      if (this.visible) {
        this.$set(this.formData, 'apply_funds', this.whiteData.apply_funds)
        this.$set(this.formData, 'load_years', this.whiteData.load_years)
        this.$set(this.formData, 'funds_use_dir', this.whiteData.funds_use_dir)
      }
    },
  },
  created() {},
  mounted() {},
  methods: {
    handleAccessAgencyChange(val, agency) {
      this.formData.recommend_service_name = agency.service_agency_name || ''
    },
    beforeClose() {
      this.resetForm()
      this.$emit('update:visible', false)
    },

    handleSelectBank(bank) {
      this.formData.public_bank_names = bank.agency_name
    },

    handleSelectBankId(bank) {
      this.formData.bank_name = bank.agency_name
    },

    submit() {
      this.validateForm()
        .then(() => {
          const data = {
            project_type: this.isRoutine ? 1 : 3,
            submit_type: 2,
            is_poverty_project: 0,
            service_id: this.clientId,
            service_name: this.org.orgName,
            submit_person_name: this.user.userName,
            submit_client_id: this.clientId,
            submit_client_name: this.org.orgName,

            ...this.formData,
            ...this.copyFromWhiteData(),
            res_person_risk_point: (this.$refs.risk && this.$refs.risk.getSelectedName()) || '',
            res_a_name: this.$refs.resA.getSelectedName(),
            res_b_name: this.$refs.resB.getSelectedName(),
          }
          if (!this.isRoutine) {
            data.project_type_id = this.whiteData.project_type_id
            data.project_type_name = this.whiteData.project_type_name
          }
          if (+this.formData.gua_type !== 4) {
            data.res_person_risk_point = ''
            data.res_user_id_risk_point = ''
          }
          this.addFarm(data)
        })
        .catch(err => {
          this.$message.warning(err[0].message)
        })
    },
    copyFromWhiteData() {
      return [
        { from: 'customer_name' },
        { from: 'corp_name' },
        { from: 'mobile_no' },
        { from: 'address_code' },
        { from: 'address_detail' },
        { from: 'register_no' },
        { from: 'org_class' },
        { from: 'id_card', to: 'lender_idcard' },
        { from: 'business_scope' },
        { from: 'main_business' },
        { from: 'parent_main_business' },
        { from: 'poverty_households' },
        { from: 'project_white_list_id' },
      ].reduce((res, ft) => {
        const { from, to } = ft
        res[to || from] = this.whiteData[from]
        return res
      }, {})
    },
    addFarm(data) {
      this.submitLoading = true
      this.$api
        .addData(this.$serviceName, this.tableName, data)
        .then(() => {
          this.$message.success('添加客户成功！')
          this.beforeClose()
          this.$emit('success', true)
        })
        .catch(err => {
          const errStr = err && err.data && typeof err.data === 'string'
          this.$message.error(errStr || '添加客户失败，请重试！')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    validateForm() {
      const enumValid = {
        gua_type: '请选择项目类型',
        res_a: '请选择项目负责人A角',
        res_b: '请选择项目负责人B角',
      }
      return new Promise((resolve, reject) => {
        const keys = Object.keys(enumValid)
        const unvalids = []
        for (const key of keys) {
          if (this.formData[key]) continue
          unvalids.push({ key, message: enumValid[key] })
        }
        if (+this.formData.gua_type === 4 && !this.formData.res_user_id_risk_point) {
          unvalids.push({ key: 'res_user_id_risk_point', message: '请选择项目风控员' })
        }
        if (unvalids.length) {
          reject(unvalids)
        } else {
          resolve()
        }
      })
    },
    resetForm() {
      Object.keys(this.formData).forEach(key => (this.formData[key] = ''))
      this.formData.gua_type = 2
    },
  },
}
</script>

<style lang="scss" scoped>
.wl-title {
  font-size: 1.2rem;
}
</style>
